export default {
	// 开启命名空间
	namespaced:true,
	state: ()=>({
		//购物车数组,用来存储购物车中每个商品的信息对象
		cart: JSON.parse(uni.getStorageSync('cart') || '[]')
		
	}),
	mutations:{
		addToCart(state,goods){
			const reslut = state.cart.find(x => x.goods_id == goods.goods_id);
			if (!reslut) {
				state.cart.push(goods)
			}else {
				reslut.goods_count++;
			}	
			this.commit('m_cart/saveToStorage')
					
		},
		// 更新商品状态
		updateGoodsState(state,goods) {
			const reslut = state.cart.find(x => x.goods_id == goods.goods_id);
			if (reslut) {
				reslut.goods_state = goods.goods_state;
			}
			this.commit('m_cart/saveToStorage')
		},
		// 更新产品数量
		updateGoodsNumState(state,goods) {
			const reslut = state.cart.find(x => x.goods_id == goods.goods_id);
				if (reslut) {
					reslut.goods_count = goods.goods_count;
				}
				this.commit('m_cart/saveToStorage')
		},
		saveToStorage(state) {
			// console.log(JSON.stringify(state.cart))
			uni.setStorageSync('cart',JSON.stringify(state.cart))
		},
		removeGoodsById(state,goods_id) {
			state.cart = state.cart.filter( x=> x.goods_id != goods_id),
			this.commit('m_cart/saveToStorage')
		},
			
		uncheckGoods(state,checkState) {
			console.log(checkState);
			state.cart.forEach(x=> x.goods_state=checkState);
			
		// 	state.cart = state.cart.forEach(item=> 
		// 		item.goods_state = checkState
		// 	);
		
		// 	this.commit('m_cart/saveToStorage')
		}
		
	},
	getters:{
		total(state) {
			// let c = 0;
			// state.cart.forEach(x=> c += x.goods_count);
			// return c;
			
			return state.cart.reduce((total,item)=> total += item.goods_count,0);
		},
		checkedCount(state) {
			return state.cart.filter(x=>x.goods_state)
			.reduce((total,item)=> total += item.goods_count,0)
		},
		
		totalPrice(state) {
			let totalPrice = 0;
			state.cart.filter(x=>x.goods_state).forEach(item=> totalPrice+=item.goods_price * item.goods_count);
			return totalPrice.toFixed(2);
		}
	}
}